<script>
import EditUserInfo from "./components/editUserInfo.vue"
import loginInfo from './util/loginInfo'
import multiavatar from '@multiavatar/multiavatar/esm'
export default {
    components: {
        EditUserInfo
    },
    data() {
        return {
            tableData: [
                // {
                //     "userId": 123,
                //     "userEmail": "abc@email.com",
                //     "userStuId": "202108010500",
                //     "userName": "张三",
                //     "userGender": 1,
                //     "userAge": 16,
                //     "userBio": "这是简介",
                //     "userGroup": 1
                // }
            ],
            currentUser: {
                userId: null
            },
            searchForm: {
                name: '',
                gender: 3,
                email: '',
                stuId: '',
                group: 3
            },
            pagination: {
                pageSize: 10,
                currentPage: 1,
                total: 1
            },
            addDialogVisible: false,
            editingUser: {},
            editingUserIndex: 0,
            editDialogVisible: false,
        }
    },
    async mounted() {
        this.currentUser.userId = loginInfo.user.userId
        this.$http.get('/users', {
            headers: {
                'token': loginInfo.getToken()
            }
        }).then((v) => {
            this.tableData = v.data.users
            this.pagination.total = v.data['total-count']
        })
    },
    methods: {
        multiavatar,
        editUser(index) {
            this.editDialogVisible = true;
            this.editingUserIndex = index
            this.editingUser = { ...this.tableData[index] }
            this.editingUser.userStuId = +this.editingUser.userStuId
        },
        addUser() {
            this.addDialogVisible = true;
            this.editingUserIndex = 0
            this.editingUser = {
                "userId": '',
                "userEmail": "",
                "userStuId": "",
                "userName": "",
                "userGender": 0,
                "userAge": 0,
                "userBio": "",
                "userGroup": 1
            }
        },
        onSaveAddUser(data) {
            this.$http.post(`/users`, {
                "userEmail": data.userEmail,
                "userStuId": data.userStuId + '',
                "userName": data.userName,
                "userGender": data.userGender,
                "userAge": data.userAge,
                "userBio": data.userBio,
                "userGroup": data.userGroup
            }, {
                headers: {
                    'token': loginInfo.getToken()
                }
            }).then((v) => {
                if (v.status == 200) {
                    this.$message.success('新增成功')
                    if (this.addDialogVisible) {
                        this.addDialogVisible = false;
                    }
                    this.tableData.unshift({ ...data, userId: v.data.userId })
                } else {
                    this.$message.error(v.msg)
                }
            })
        },
        onSave(data, msg = '修改成功！') {
            this.$http.put(`/users/${data.userId}`, {
                "userEmail": data.userEmail,
                "userStuId": data.userStuId + '',
                "userName": data.userName,
                "userGender": data.userGender,
                "userAge": data.userAge,
                "userBio": data.userBio,
                "userGroup": data.userGroup
            }, {
                headers: {
                    'token': loginInfo.getToken()
                }
            }).then((v) => {
                if (v.status == 200) {
                    this.$message.success(msg)
                    if (this.editDialogVisible) {
                        this.editDialogVisible = false;
                    }
                    this.tableData[this.editingUserIndex] = { ...data }
                } else {
                    this.$message.error(v.msg)
                }
            })
        },
        modifyPwd(id) {
            this.$prompt('请输入新密码：', '修改密码', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern:
                    /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{8,16}$/,
                inputErrorMessage: '密码不符合要求',
            })
                .then(({ value }) => {
                    this.$http.put(`/users/${id}/password`, {
                        "userNewPwd": value
                    }, {
                        headers: {
                            'token': loginInfo.getToken()
                        }
                    }).then((v) => {
                        if (v.status == 200) {
                            this.$message.success('修改密码成功！')
                        } else {
                            this.$message.error(v.msg)
                        }
                    })

                })
                .catch(() => {

                })
        },
        onCurrentPageChange(val) {
            this.pagination.currentPage = val
            this.onSearch()
        },
        onPageSizeChange(val) {
            this.pagination.currentPage = 1
            this.pagination.pageSize = val
            this.onSearch()
        },
        onRestoreUser(index) {
            let data = this.tableData[index]
            this.editingUserIndex = index
            this.onSave({
                "userId": data.userId,
                "userEmail": data.userEmail,
                "userStuId": data.userStuId + '',
                "userName": data.userName,
                "userGender": data.userGender,
                "userAge": data.userAge,
                "userBio": data.userBio,
                "userGroup": 1
            }, '恢复成功！')
        },
        onRemoveUser(index) {
            let data = this.tableData[index]
            this.editingUserIndex = index
            this.onSave({
                "userId": data.userId,
                "userEmail": data.userEmail,
                "userStuId": data.userStuId + '',
                "userName": data.userName,
                "userGender": data.userGender,
                "userAge": data.userAge,
                "userBio": data.userBio,
                "userGroup": 2
            }, '禁用成功！')
        },
        onSearch(clickBtn = false) {
            if (clickBtn) {
                this.pagination.currentPage = 1
            }
            let obj = {}
            let form = this.searchForm
            if (form.name !== '') {
                obj.name = form.name
            }
            if (form.gender !== 3) {
                obj.gender = form.gender
            }
            if (form.email !== '') {
                obj.email = form.email
            }
            if (form.stuId !== '') {
                obj.stuId = form.stuId
            }
            if (form.group !== 3) {
                obj.group = form.group
            }

            obj.page = this.pagination.currentPage
            obj['page-size'] = this.pagination.pageSize

            this.$http.get('/users', {
                headers: {
                    'token': loginInfo.getToken()
                },
                params: {
                    ...obj
                }
            }).then((v) => {
                this.tableData = v.data.users
                this.pagination.total = v.data['total-count']
            })
        },
        onSearchRecords(userId) {
            this.$router.push({ path: '/records', query: { userId } })
        },
        cellClick(row, column, cell, event) {
            if (column.no == 1) {
                this.searchForm.email = row.userEmail
            }
            if (column.no == 3) {
                this.searchForm.name = row.userName
            }
        }
    }
}
</script>

<template>
    <div>
        <el-card shadow="never">
            <el-form :inline="true" :model="searchForm">
                <el-row>
                    <el-col>
                        <el-form-item label="邮箱">
                            <el-input clearable v-model="searchForm.email" placeholder="邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="学号">
                            <el-input clearable v-model="searchForm.stuId" placeholder="学号"></el-input>
                        </el-form-item>
                        <el-form-item label="姓名">
                            <el-input clearable v-model="searchForm.name" placeholder="姓名"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="性别">
                            <el-select placeholder="性别" v-model="searchForm.gender">
                                <el-option label="全部" :value="3"></el-option>
                                <el-option label="未知" :value="0"></el-option>
                                <el-option label="男" :value="1"></el-option>
                                <el-option label="女" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="用户组">
                            <el-select placeholder="用户组" v-model="searchForm.group">
                                <el-option label="全部" :value="3"></el-option>
                                <el-option label="管理员" :value="0"></el-option>
                                <el-option label="普通用户" :value="1"></el-option>
                                <el-option label="禁用用户" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="onSearch(true)" icon="search" type="primary">搜索</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-table
                @cell-click="cellClick"
                :height="350"
                :data="tableData"
                border
                style="margin: 20px 0;"
            >
                <el-table-column label="头像" width="60">
                    <template #default="scope">
                        <div v-html="multiavatar(scope.row.userId)"></div>
                    </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip prop="userEmail" label="邮箱" max-width="300" />
                <el-table-column prop="userStuId" label="学号" width="150" />
                <el-table-column prop="userName" label="姓名" width="180" />
                <el-table-column label="性别" width="60">
                    <template #default="scope">
                        <span v-if="scope.row.userGender === 1">男</span>
                        <span v-if="scope.row.userGender === 2">女</span>
                    </template>
                </el-table-column>
                <el-table-column prop="userAge" label="年龄" width="60" />
                <el-table-column label="简介" width="60">
                    <template #default="scope">
                        <el-popover
                            v-if="scope.row.userBio != ''"
                            placement="bottom"
                            :width="200"
                            trigger="hover"
                            :content="scope.row.userBio"
                        >
                            <template #reference>
                                <el-link type="primary">详情</el-link>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="userGroup" label="用户组" width="90">
                    <template #default="scope">
                        <span v-if="scope.row.userGroup === 0">管理员</span>
                        <span v-else-if="scope.row.userGroup === 1">普通用户</span>
                        <span v-else-if="scope.row.userGroup === 2">禁用</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="500">
                    <template #header>
                        <span style="margin-right: 10px;">操作</span>
                        <el-button @click="addUser" type="success" icon="plus">新增用户</el-button>
                    </template>
                    <template #default="scope">
                        <el-button
                            @click="onSearchRecords(scope.row.userId)"
                            type="success"
                            plain
                            icon="search"
                        >查询借阅记录</el-button>
                        <el-button
                            type="primary"
                            icon="RefreshRight"
                            v-if="scope.row.userGroup === 2"
                            @click="onRestoreUser(scope.$index)"
                        >恢复</el-button>
                        <template v-else-if="scope.row.userId != currentUser.userId">
                            <el-button
                                type="warning"
                                plain
                                @click="modifyPwd(scope.row.userId)"
                                icon="Edit"
                            >修改密码</el-button>
                            <el-button
                                type="warning"
                                icon="EditPen"
                                @click="editUser(scope.$index)"
                            >编辑</el-button>
                            <el-popconfirm
                                confirm-button-text="确定"
                                cancel-button-text="取消"
                                icon="InfoFilled"
                                icon-color="red"
                                @confirm="onRemoveUser(scope.$index)"
                                title="确定要删除吗？"
                            >
                                <template #reference>
                                    <el-button type="danger" icon="delete">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @current-change="onCurrentPageChange"
                @size-change="onPageSizeChange"
                :page-sizes="[10, 15, 20]"
                background
                :current-page="pagination.currentPage"
                layout="sizes, prev, pager, next, jumper"
                :total="pagination.total"
            ></el-pagination>
        </el-card>
        <!-- 编辑对话框 -->
        <el-dialog v-model="editDialogVisible" :title="'编辑用户 ' + editingUser.userId">
            <EditUserInfo :hasGroup="true" style="width: 60%;" @submit="onSave" :data="editingUser"></EditUserInfo>
            <EditUserInfo
                v-show="editMode == 'add'"
                :hasGroup="true"
                style="width: 60%;"
                @submit="onSaveAddUser"
                :data="editingUser"
            ></EditUserInfo>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 新增对话框 -->
        <el-dialog v-model="addDialogVisible" :title="'新增用户'">
            <EditUserInfo
                :hasGroup="true"
                style="width: 60%;"
                @submit="onSaveAddUser"
                :data="editingUser"
            ></EditUserInfo>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style>
</style>